package cn.com.tom.servlet;

import cn.com.tom.bean.User;
import cn.com.tom.service.SkillService;
import cn.com.tom.service.UserService;
import cn.com.tom.service.WebsiteService;
import cn.com.tom.service.impl.SkillServiceImpl;
import cn.com.tom.service.impl.UserServiceImpl;
import cn.com.tom.service.impl.WebsiteServiceImpl;
import cn.com.tom.util.Uploads;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.*;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    UserService servie = new UserServiceImpl();
    SkillService skillService = new SkillServiceImpl();
    WebsiteService websiteService = new WebsiteServiceImpl();

    public void admin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<User> list = servie.list();
        request.setAttribute("user", list.get(0));
        forward(request, response, "admin/user.jsp");
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String imagePath = "";
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        upload.setHeaderEncoding("UTF-8");
        Map<String, Object> map = new HashMap<>();
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem item : fileItems) {
            if (item.isFormField()) {//1:非文件
                map.put(item.getFieldName(), item.getString("UTF-8"));
            } else {//2:文件
                if ("photoFile".equals(item.getFieldName())) {
                    imagePath = Uploads.uploadImage(item, request);
                }
            }
        }
        User bean = new User();
        BeanUtils.populate(bean, map);
        if (imagePath != null && !"".equals(imagePath)) {
            bean.setPhoto(imagePath);
        }

        User user = (User) request.getSession().getAttribute("user");
        bean.setPassword(user.getPassword());
        bean.setEmail(user.getEmail());
        if (servie.save(bean)) {
            request.getSession().setAttribute("user", bean);
            redirect(request, response, "/user/admin");
        } else {
            forwardError(request, response, "保存失败");
        }
    }

    public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] idS = request.getParameterValues("id");
        List<Integer> list = new ArrayList();
        for (int i = 0; i < idS.length; i++) {
            list.add(Integer.valueOf(idS[i]));
        }
        if (servie.remove(list)) {
            redirect(request, response, "/user/admin");
        } else {
            forwardError(request, response, "保存失败");
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //1:先验证验证码
        String code = request.getParameter("captcha");
        if ("".equals(code) || code == null) {
            forwardError(request, response, "验证码有误");
            return;
        }
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (!code.toLowerCase().equals(captcha)) {
            forwardError(request, response, "验证码有误");
            return;
        }

        //2:再验证用户名和密码
        User user = new User();
        BeanUtils.populate(user, request.getParameterMap());
        user = servie.getUser(user);
        if (user != null) {//登录成功把user对象放到会话里面
            request.getSession().setAttribute("user", user);
            redirect(request, response, "/user/admin");
        } else {
            forwardError(request, response, "账号或者密码错误");
        }
    }

    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {

        DefaultKaptcha db = new DefaultKaptcha();
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("kaptcha.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        Config config = new Config(properties);
        db.setConfig(config);

        String code = db.createText();

        HttpSession session = request.getSession();
        session.setAttribute("captcha", code.toLowerCase());

        BufferedImage image = db.createImage(code);
        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().removeAttribute("user");
        redirect(request, response, "/login.jsp");
    }

    public void front(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = servie.list().get(0);
        String[] traits = user.getTrait().split(",");
        String[] interests = user.getInterests().split(",");

        request.setAttribute("user", user);
        request.setAttribute("interests", interests);
        request.setAttribute("traits", traits);
        request.setAttribute("website", websiteService.list().get(0));
        request.setAttribute("skills", skillService.list());
        forward(request, response, "front/user.jsp");
    }

    public void password(HttpServletRequest request, HttpServletResponse response) throws Exception {
        forward(request, response, "admin/password.jsp");
    }

    public void editpwd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String oldPassword = request.getParameter("oldPassword");
        String password = request.getParameter("password");
        User bean = (User) request.getSession().getAttribute("user");
        if (!oldPassword.equals(bean.getPassword())) {
            forwardError(request, response, "旧密码错误");
            return;
        }
        bean.setPassword(password);
        if (servie.save(bean)) {
            redirect(request, response, "/login.jsp");
        } else {
            forwardError(request, response, "保存失败");
        }
    }
}
